
package com.bear.cmcc.NetTestHTTP.ui.activity;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources.NotFoundException;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo.State;
import android.os.Bundle;
import android.os.Handler;
import android.telephony.CellLocation;
import android.telephony.PhoneStateListener;
import android.telephony.SignalStrength;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.bear.cmcc.NetTestHTTP.NetworkTestApp;
import com.bear.cmcc.NetTestHTTP.R;
import com.bear.cmcc.NetTestHTTP.component.CountryBean;
import com.bear.cmcc.NetTestHTTP.component.HttpTestRoundInfoBean;
import com.bear.cmcc.NetTestHTTP.component.NetTestLogBean;
import com.bear.cmcc.NetTestHTTP.component.NetTestSpeedBean;
import com.bear.cmcc.NetTestHTTP.component.PowerLock;
import com.bear.cmcc.NetTestHTTP.constant.HttpTestActivityConstant;
import com.bear.cmcc.NetTestHTTP.constant.MyCommonConstant;
import com.bear.cmcc.NetTestHTTP.constant.NetTestDBConstant;
import com.bear.cmcc.NetTestHTTP.constant.NetTestDBConstant.TestTimesFiledName;
import com.bear.cmcc.NetTestHTTP.service.HttpTestService;
import com.bear.cmcc.NetTestHTTP.service.NetTestService;
import com.bear.cmcc.NetTestHTTP.ui.adapter.HttpTestExpListAdapter;
import com.bear.cmcc.NetTestHTTP.ui.adapter.TimeAdapter;
import com.bear.cmcc.NetTestHTTP.ui.chart.TestToolChartView;
import com.bear.cmcc.NetTestHTTP.util.CountryUtil;
import com.bear.cmcc.NetTestHTTP.util.HttpTestUtils;
import com.bear.cmcc.NetTestHTTP.util.MyCommonUtil;
import com.bear.cmcc.NetTestHTTP.util.NetTestUtil;
import com.bear.cmcc.NetTestHTTP.util.SetUtil;
import com.bear.cmcc.NetTestHTTP.util.TimeUtil;

public class HttpTestActivity extends AbstractActivity {
    private static final String TAG = HttpTestActivity.class.getSimpleName();

    // 小区信息
    private TextView tvCellValue, tvLacValue, tvCiValue, tvSignalValue, tvNetType,
            tvWlanSignalValue;

    private String mVilliageName;

    private LinearLayout lyNoWlan;

    private LinearLayout lyWlan;

    // 选择模块
    private Button timesNumValue;

    private Button startButton;

    private TimeAdapter timeAdapter;

    private TimeAdapter timeAdapterGroup;

    private boolean isTimes = true;

    private CountryBean mCountryBean;

    private NetTestLogBean mNetLogBean = new NetTestLogBean();

    private PopupWindow popupWindow;

    private PopupWindow listPopupWindow;

    // 图表模块
    private TestToolChartView mTestToolChartView;

    // 图表布局
    private LinearLayout lyChart;

    // 图表view
    private View mChartView;

    // 图表显示状态
    private boolean isShowChart = false;

    private boolean isFristRefresh = false;

    private double mMaxSpeed = 0;

    private double mTempMaxSpeed = 0;

    private double mMinSpeed = 0;

    private double mAveSpeed = 0;

    private boolean mTimeSuccess = false;

    private int mTimeIdx = 0;

    private int mSelectTimesIdx = 0;

    // private int mGroupPop = -1;

    private int mGroupPid = -1;

    // 列表信息
    private List<HttpTestRoundInfoBean> groupList = new ArrayList<HttpTestRoundInfoBean>();

    private List<List<Map<String, Object>>> childList = new ArrayList<List<Map<String, Object>>>();

    private NetTestSpeedBean speedItem = new NetTestSpeedBean();

    HttpTestExpListAdapter adapter;

    ExpandableListView exList;

    // 屏幕长亮控制
    PowerLock lock;

    // 测试服务广播接收
    private NetTestServiceReceiver serviceReceiver = new NetTestServiceReceiver();

    // 导入小区数据广播接收
    private ImportDataReceiver importReceiver = new ImportDataReceiver();

    // 网络变化广播接收
    private ConnectionChangeReceiver connectionReceiver = new ConnectionChangeReceiver();

    // 信号强度值
    private int netStrong = 0;

    // 信号强度值监听
    private HttpTestActivityPhoneStateListener signalListener;

    // 刷新图表计时器
    private Timer timer = new Timer(true);

    private TimerTask timerTask = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        loadBottomBar();
        choseBottomItemIndex(MyCommonConstant.TEST_ACTIVITY_INDEX);
        setTitle(R.string.title_http_test);
        setContentView(R.layout.activity_httptest);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        layoutInit();
        popupWindowInit();
        getHeadData();
        // 注册导入数据广播
        registerImportDataBroadCast();
        // 注册网络变化广播
        registerNetChangeBroadCast();
        registerNettestServiceBroadCast();
        // 还原测试状态
        returnTestState();
        listenSignalValue();

        refreshHandler.sendEmptyMessage(HttpTestActivityConstant.HandlerCode.listRefreshDispose);
    }

    @Override
    protected void onStart() {
        choseBottomItemIndex(MyCommonConstant.TEST_ACTIVITY_INDEX);
        super.onStart();
    }

    /**
     * activity
     */
    @Override
    protected void onDestroy() {
        if (isShowChart) {
            if (!isTimes) {
                mSelectTimesIdx = -1;
            }
            SetUtil.setHttpTestRuningTimes(mSelectTimesIdx, this);
            // 保存测试服务状态
            SetUtil.setHttpTestRuningState(true, this);
        } else {
            SetUtil.setHttpTestRuningState(false, this);
        }
        closeHandler();
        this.unregisterReceiver(importReceiver);
        this.unregisterReceiver(connectionReceiver);
        stopChartTimer();
        super.onDestroy();
    }

    @Override
    protected void onStop() {
        if (SetUtil.getHttpTestRuningState(this)) {
            if (!isTimes) {
                mSelectTimesIdx = -1;
            }
            // 保存测试状态
            SetUtil.setHttpTestRuningTimes(mSelectTimesIdx, this);
            // 保存测试服务状态

        }

        super.onStop();
    }

    private void stopChartTimer() {
        try {
            if (timerTask != null) {
                timerTask.cancel();
                timerTask = null;
            }
            if (timer != null) {
                timer.purge();
            }
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }

    private void startChartTimer() {
        try {
            if (timerTask != null) {
                timerTask.cancel();
                timerTask = null;
            }
            if (timer != null) {
                timer.purge();
            }
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        refreshHandler.sendEmptyMessage(HttpTestActivityConstant.HandlerCode.ChartRefreshDispose);
        timerTask = new TimerTask() {

            @Override
            public void run() {
                try {
                    refreshHandler
                            .sendEmptyMessage(HttpTestActivityConstant.HandlerCode.ChartRefreshDispose);

                } catch (Exception e) {
                    if (e != null) {
                        e.printStackTrace();
                    }
                } finally {

                }

            }

        };
        if (timer != null) {
            timer.schedule(timerTask, 0, 1000);
        }
    }

    /**
     * 添加信号强度和网络切换监听
     */
    private void listenSignalValue() {
        signalListener = new HttpTestActivityPhoneStateListener();
        TelephonyManager telManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        telManager.listen(signalListener, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
    }

    /**
     * 还原service状态
     */
    private void returnTestState() {
        if (MyCommonUtil.isServiceRun(this, HttpTestService.class.getName())) {
            if (SetUtil.getHttpTestRuningState(this)) {
                if (!isShowChart) {
                    isShowChart = true;
                    mSelectTimesIdx = SetUtil.getHttpTestRuningTimes(this);
                    if (mSelectTimesIdx == -1) {
                        isTimes = true;
                        chooseNoTimes();
                    } else {
                        isTimes = false;
                        chooseTimes(mSelectTimesIdx);
                    }
                    startButton.setText(R.string.stop_test);
                    startButton.setBackgroundResource(R.drawable.stoptest_btn);
                    mTestToolChartView = new TestToolChartView();
                    mChartView = mTestToolChartView.obtainChartView(this);
                    lyChart.addView(mChartView, new LayoutParams(LayoutParams.MATCH_PARENT, 125));
                    timesNumValue.setClickable(false);
                    mAveSpeed = 0;
                    startChartTimer();
                    
                }
            }

        }
    }

    /**
     * 注册网络状态变化监听广播
     */
    private void registerNetChangeBroadCast() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(connectionReceiver, filter);
    }

    /**
     * 注册nettest服务数据广播
     */
    private void registerNettestServiceBroadCast() {
        // 注册nettest服务数据广播
        IntentFilter filter = new IntentFilter();
        filter.addAction(MyCommonConstant.PrivateActionName.HTTP_TEST_ONE_ROUND_BEGIN_BROAD);
        filter.addAction(MyCommonConstant.PrivateActionName.HTTP_TEST_ONE_ROUND_FINISH_BROAD);
        filter.addAction(MyCommonConstant.PrivateActionName.HTTP_TEST_ONE_TIME_FINISH_BROAD);
        filter.addAction(MyCommonConstant.PrivateActionName.HTTP_TEST_SPEED_BROAD);

        this.registerReceiver(serviceReceiver, filter);
    }

    /**
     * 注册导入数据广播
     */
    private void registerImportDataBroadCast() {
        // 注册导入数据广播
        IntentFilter filter = new IntentFilter();
        filter.addAction(MyCommonConstant.PrivateActionName.IMPORT_DATA_FINISH_BROAD);
        filter.addAction(MyCommonConstant.PrivateActionName.NET_TEST_ONE_ROUND_FINISH_BROAD);

        this.registerReceiver(importReceiver, filter);
    }

    /**
     * 开始测试
     */
    private void startTest() {

        try {
            isFristRefresh = false;

            startChartTimer();

            timesNumValue.setClickable(false);

            startButton.setText(R.string.stop_test);
            startButton.setBackgroundResource(R.drawable.stoptest_btn);


            int timeNum = 1;
            if (isTimes) {
                // timeNum =
                // Integer.parseInt(timesNumValue.getText().toString());
                Log.i(TAG, "mSelectTimesIdx " + mSelectTimesIdx);
                switch (mSelectTimesIdx) {
                    case 0:
                        timeNum = 1;
                        break;
                    case 1:
                        timeNum = 3;
                        break;
                    case 2:
                        timeNum = 10;
                        break;
                    case 3:
                        timeNum = 100;
                        break;
                }
            } else {
                timeNum = HttpTestActivityConstant.NETTEST_SERVICE_TEST_NUM.continue_test_num;
            }
            HttpTestUtils.startHttpTestService(this, 0);
            SetUtil.setHttpTestRuningState(true, this);

            lock = new PowerLock(HttpTestActivity.this, "HttpTestActivity");
            if (lock != null) {
                lock.acquireWakeLock();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void backTestState() {
        if (lock != null) {
            lock.releaseWakeLock();
        }
        // 停止
        stopChartTimer();

        startButton.setText(R.string.start_test);
        startButton.setBackgroundResource(R.drawable.starttest_btn);

        timesNumValue.setClickable(true);
    }

    /**
     * 停止测试
     */
    private void stopTest() {

        backTestState();
        try {
            if (groupList.size() > 0) {
                HttpTestUtils.stopHttpTestService(this, groupList.get(0).getPID());
            } else {
                HttpTestUtils.stopHttpTestService(this, 0);
            }
            SetUtil.setHttpTestRuningState(false, HttpTestActivity.this);
//            this.unregisterReceiver(serviceReceiver);
        } catch (Exception e) {
        }
        refreshHandler.sendEmptyMessage(HttpTestActivityConstant.HandlerCode.listRefreshDispose);

    }

    /**
     * 展开图表显示
     */
    private void showChart() {
        isShowChart = true;
        startButton.setText(R.string.stop_test);
        startButton.setBackgroundResource(R.drawable.stoptest_btn);
        mTestToolChartView = new TestToolChartView();
        mChartView = mTestToolChartView.obtainChartView(this);
        lyChart.addView(mChartView, new LayoutParams(LayoutParams.MATCH_PARENT, 125));
    }

    /**
     * 关闭图表显示
     */
    private void CloseChart() {
        if (isShowChart) {
            isShowChart = false;
            // 移除波形图
            lyChart.removeAllViews();
            // 关闭列表实时速度显示
            CloseListSpeed();
            // 还原测试状态
            backTestState();
            refreshHandler.sendEmptyMessage(HttpTestActivityConstant.HandlerCode.listRefreshDispose);

        } else {
            refreshHandler.sendEmptyMessage(HttpTestActivityConstant.HandlerCode.listRefreshDispose);
        }

    }

    /**
     * 关闭列表速度显示
     */
    private void CloseListSpeed() {
        mAveSpeed = 0;
        mMaxSpeed = 0;
        mMinSpeed = 0;
        if (speedItem != null) {
            speedItem.setShow(false);
        }
        Log.d("speedItem", String.valueOf(speedItem.getShow()));
        if (adapter != null) {
            adapter.notifyDataSetChanged();
        }
    }

    /**
     * 
     */
    @Override
    protected void CloseServerDispose() {
        if (isShowChart) {
            refreshHandler.sendEmptyMessage(HttpTestActivityConstant.HandlerCode.RoundDispose);
        }
    }

    /**
     * 布局初始化
     */
    private void layoutInit() {
        lyNoWlan = (LinearLayout) findViewById(R.id.lyNotWlan);
        lyWlan = (LinearLayout) findViewById(R.id.lyWlan);

        tvCellValue = (TextView) findViewById(R.id.tvCellValue);
        tvLacValue = (TextView) findViewById(R.id.tvLacValue);
        tvCiValue = (TextView) findViewById(R.id.tvCiValue);
        tvSignalValue = (TextView) findViewById(R.id.tvSignalValue);
        tvWlanSignalValue = (TextView) findViewById(R.id.tvWlanSignalValue);
        tvNetType = (TextView) findViewById(R.id.tvNetTypeValue);

        lyChart = (LinearLayout) findViewById(R.id.layoutChart);

        timesNumValue = (Button) findViewById(R.id.timesNumValue);
        timesNumValue.setOnClickListener(onButtonClick);
        startButton = ((Button) findViewById(R.id.buttonDownload));
        startButton.setOnClickListener(onButtonClick);

        exList = (ExpandableListView) findViewById(R.id.expandableListView);
        adapter = new HttpTestExpListAdapter(this, this, groupList, childList,
                speedItem);
        exList.setAdapter(adapter);
        exList.setDivider(null);
        exList.setDividerHeight(2);
        exList.setGroupIndicator(null);

        exList.setOnChildClickListener(childsListener);

        exList.setOnItemLongClickListener(exListLongTouchListener);
        // exList.setOnTouchListener(onTouchListener);
    }

    /**
     * 重载abstract 接口 屏蔽重复点击底部栏按钮操作
     */
    protected void responseForTestTool() {

    }

    /**
     * 刷新列表数据
     */
    private void refreshListData() {
        groupList.clear();
        childList.clear();
        ArrayList<HttpTestRoundInfoBean> groups = HttpTestUtils.getHttpTestRoundsInfos(
        		HttpTestActivity.this, false);
        if (groups != null) {
            for (int i = 0; i < groups.size(); i++) {
   
                String consumeTime = TimeUtil.secondBetweenTime(groups.get(i).getStartTime(),
                        groups.get(i).getEndTime()) + getResources().getString(R.string.sec_unit);
                groups.get(i).setConsumeTime(consumeTime);
                groupList.add(groups.get(i));
            }

        }
        if (isShowChart) {
            exList.expandGroup(0);
        }
        adapter.notifyDataSetChanged();

    }

    /**
     * 弹出次数选择框
     * 
     * @View v
     */
    private void showPopupWidow(View v) {
        popupWindow.showAsDropDown(v);
    }

    /**
     * 长按list弹出菜单
     * 
     * @param v
     */
    private void showListPopupWidow(View v) {
        LinearLayout lyParent = (LinearLayout) findViewById(R.id.parent);
        listPopupWindow.showAtLocation(lyParent, Gravity.CENTER_VERTICAL, 0, 0);
    }

    /**
     * 弹出选择次数框
     */
    private void popupWindowInit() {
        timeAdapter = new TimeAdapter(this, getResources().getStringArray(R.array.http_url_array));
        ListView timeListView = (ListView) LayoutInflater.from(this).inflate(
                R.layout.layout_popuptime, null);
        timeListView.setAdapter(timeAdapter);
        LayoutParams lp = timesNumValue.getLayoutParams();
        popupWindow = new PopupWindow(timeListView, lp.width, LayoutParams.WRAP_CONTENT, true);
        Drawable popBg = getResources().getDrawable(R.drawable.pop_bg);
        popupWindow.setBackgroundDrawable(popBg);
        popupWindow.setFocusable(true);
        timeListView.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                popupWindow.dismiss();
                mSelectTimesIdx = arg2;
                timesNumValue.setText(timeAdapter.getItem(arg2).toString());
            }
        });
    }

    /**
     * 确认删除对话框
     */
    public void ConfirmDelete() {// 退出确认
        AlertDialog.Builder ad = new AlertDialog.Builder(HttpTestActivity.this);
        ad.setTitle(R.string.dlg_note_title);
        ad.setMessage(R.string.dlg_note_content_delete);
        ad.setPositiveButton(R.string.dlg_note_btn_confirm, new DialogInterface.OnClickListener() {// 退出按钮
                    @Override
                    public void onClick(DialogInterface dialog, int i) {
                        if (mGroupPid != -1) {
                            deleteRound(mGroupPid);
                        }
                    }
                });
        ad.setNegativeButton(R.string.dlg_note_btn_cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int i) {
                // 不退出不用执行任何操作
            }
        });
        ad.show();// 显示对话框
    }

    // /**
    // * 弹出group操作选择框
    // */
    // private void popupGroupWindowInit(View view) {
    // timeAdapterGroup = new TimeAdapter(this,
    // getResources().getStringArray(R.array.group_array));
    // ListView timeListView = (ListView) LayoutInflater.from(this).inflate(
    // R.layout.layout_popuptime, null);
    // timeListView.setAdapter(timeAdapterGroup);
    //
    // LayoutParams lp = view.getLayoutParams();
    // listPopupWindow = new PopupWindow(timeListView, lp.width,
    // LayoutParams.WRAP_CONTENT, true);
    // listPopupWindow.setBackgroundDrawable(new BitmapDrawable());
    // listPopupWindow.setFocusable(true);
    //
    // timeListView.setOnItemClickListener(new OnItemClickListener() {
    // public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long
    // arg3) {
    // listPopupWindow.dismiss();
    // final int roundId=(Integer) arg1.getTag(R.string.group_item_pid);
    // switch (arg2) {
    // case 0: {
    // mGroupPid = roundId;
    // ConfirmDelete();
    // }
    // break;
    // case 1: {
    // NetTestRoundInfoBean testInfo = getRoundById(roundId);
    // MyCommonUtil.share(HttpTestActivity.this, getString(R.string.share),
    // setShareData(testInfo));
    // }
    // break;
    // case 2: {
    // reportGenerate(roundId);
    // }
    // break;
    // }
    // }
    // });
    // }

    private String setShareData(HttpTestRoundInfoBean testInfo) {
        StringBuffer testData = new StringBuffer();
        testData.append("服务器:" + testInfo.getDownServer()).append(";");
        testData.append("最大速度:" + testInfo.getMaxSpeed()).append(";");
        testData.append("最小速度:" + testInfo.getMinSpeed()).append(";");
        testData.append("平均速度:" + testInfo.getAverageSpeed()).append(";");
        testData.append("小区名称:" + testInfo.getVillageName());
        return testData.toString();
    }

    /**
     * 获取头部信息栏数据
     */
    private void getHeadData() {
        refreshHandler.sendEmptyMessage(HttpTestActivityConstant.HandlerCode.HeadDispose);
    }

    /**
     * 移除handler消息监听，取消测试服务广播监听
     */
    private void closeHandler() {
        try {
            this.unregisterReceiver(serviceReceiver);

        } catch (Exception e1) {
            e1.printStackTrace();
        }
        try {
            this.refreshHandler.removeMessages(HttpTestActivityConstant.HandlerCode.HeadDispose);
            this.refreshHandler
                    .removeMessages(HttpTestActivityConstant.HandlerCode.ChartRefreshDispose);
            this.refreshHandler.removeMessages(HttpTestActivityConstant.HandlerCode.RoundDispose);
            this.refreshHandler
                    .removeMessages(HttpTestActivityConstant.HandlerCode.listRefreshDispose);
            this.refreshHandler.removeMessages(HttpTestActivityConstant.HandlerCode.timeDispose);
        } catch (Exception e) {
        }
    }

    /*
     * 更新图表数据
     */
    private void setChartViewData() {
        if (mTestToolChartView != null) {

            if (mAveSpeed > mTempMaxSpeed) {
                mTempMaxSpeed = mAveSpeed * 1.2;
            }

            mTestToolChartView.updateChartView(mAveSpeed, mTempMaxSpeed);
            if (speedItem != null) {
                speedItem.setAve(MyCommonUtil.getFormatString(mAveSpeed));
                speedItem.setMax(MyCommonUtil.getFormatString(mMaxSpeed));
                speedItem.setMin(MyCommonUtil.getFormatString(mMinSpeed));
                speedItem.setShow(true);
            }
            adapter.notifyDataSetChanged();
            if (exList != null && isFristRefresh == false) {
                exList.setSelection(0);
                isFristRefresh = true;
            }
        }
    }

    /**
     * 网络变化。
     * 
     * @param isConnect
     */
    protected void refreshByNetworkChange(boolean isConnect) {
        if (mCountryBean != null) {
            if (isConnect) {
                String selfNetType = MyCommonUtil.getNetWorkName(this);
                mCountryBean.setSelfNetType(selfNetType);
            }
        }
    }

    /**
     * 设置头部信息栏数据
     */
    private void setHeadData() {
        mCountryBean = CountryUtil.getProvinceNetData(HttpTestActivity.this);
        NetTestUtil.getLACCI(HttpTestActivity.this, mNetLogBean);
        if (mNetLogBean != null) {
            mVilliageName = SetUtil.getVillageName(mNetLogBean.getLac(), mNetLogBean.getCi(),
                    mCountryBean.getSelfNetType(), HttpTestActivity.this);
        }
        if (mVilliageName == null || mVilliageName.equals("")) {
            if (NetworkTestApp.getApp().getVillage() != null
                    && NetworkTestApp.getApp().getStreet() != null) {
                mVilliageName = NetworkTestApp.getApp().getVillage()
                        + NetworkTestApp.getApp().getStreet();

            }
        }

        if (MyCommonUtil.isWIFI(this)) {
            lyWlan.setVisibility(View.VISIBLE);
            lyNoWlan.setVisibility(View.GONE);
        } else {
            lyWlan.setVisibility(View.GONE);
            lyNoWlan.setVisibility(View.VISIBLE);
        }
        tvNetType.setText(mCountryBean.getSelfNetType());
        tvSignalValue.setText(String.valueOf(getNetStrong()));
        tvWlanSignalValue.setText(String.valueOf(MyCommonUtil.getWifiStrong(this)));
        tvLacValue.setText(String.valueOf(mNetLogBean.getLac()));
        tvCiValue.setText(String.valueOf(mNetLogBean.getCi()));
        tvCellValue.setText(mVilliageName);
    }

    /**
     * 生成报告跳转
     */
    public void reportGenerate(int pid) {
        Intent it = new Intent(HttpTestActivity.this, TheTestDetailActivity.class);
        it.putExtra(NetTestDBConstant.TestRoundFiledName.pid, pid);
        it.putExtra(MyCommonConstant.BottomIdxCode.bottom_dis,
                MyCommonConstant.BottomIdxCode.BOTTOM_IDX_TEST_TOOL);
        startActivity(it);
    }

    /**
     * 删除操作
     */
    public void deleteRound(int pid) {
        HttpTestUtils.deleteRoundInfo(this, pid);
        refreshListData();
    }

    /**
     * 开始测试，停止测试操作
     */
    private OnLongClickListener onLongClick = new OnLongClickListener() {
        public boolean onLongClick(View v) {
            switch (v.getId()) {
                case R.id.timesNumValue: {
                    showPopupWidow(timesNumValue);
                    return false;
                }
            }
            return false;
        }
    };

    /**
     * 手动启动测试
     */
    private void manualStartTestDispose() {

        refreshHandler.sendEmptyMessage(HttpTestActivityConstant.HandlerCode.startServiceDispose);

    }

    private void startHttpTest() {
        // 判断自动测试服务是否开启，如果已开启则关闭它
        if (MyCommonUtil.isServiceRun(this, HttpTestService.class.getName())) {
            if (!SetUtil.getHttpTestRuningState(this)) {
                HttpTestUtils.stopHttpTestService(this, 0);
            }
        }

        showChart();
        startTest();
    }

    /**
     * 手动停止测试
     */
    private void manualStopTestDispose() {
        refreshHandler.sendEmptyMessage(HttpTestActivityConstant.HandlerCode.stopServiceDispose);

    }

    /**
     * 自动停止测试
     */
    private void autoStopTestDispose() {
        CloseChart();
    }

    /**
     * 开始测试，停止测试操作
     */
    private OnClickListener onButtonClick = new OnClickListener() {
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.buttonDownload: {
                    try {
                        if (SetUtil.getHttpTestRuningState(HttpTestActivity.this)) {
                            manualStopTestDispose();
                        } else {
                            // 无网络提示
                            if (!MyCommonUtil.isNetworkAviable(HttpTestActivity.this)) {
                                Toast.makeText(HttpTestActivity.this, R.string.toast_note_net_close,
                                        Toast.LENGTH_LONG).show();
                                return;
                            }
                            manualStartTestDispose();
                        }
                    } catch (NotFoundException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                    break;
                case R.id.timesNumValue: {
                    chooseTimes(mSelectTimesIdx);
                }
                    break;
                case R.id.noTimesNumValue: {
                    chooseNoTimes();
                    // showPopupWidow(timesNumValue);
                }
                    break;
            }
        }
    };

    /**
     * 连续按钮选择
     */
    private void chooseNoTimes() {
        timesNumValue.setBackgroundResource(R.drawable.choosetimes_blank_bak);
        Drawable left = getResources().getDrawable(R.drawable.small_checked_ico);
        Drawable right = getResources().getDrawable(R.drawable.downarrow_grayico);
        left.setBounds(0, 0, left.getMinimumWidth(), left.getMinimumHeight());
        right.setBounds(0, 0, right.getMinimumWidth(), right.getMinimumHeight());
        timesNumValue.setCompoundDrawables(left, null, right, null);
        timesNumValue.setTextColor(getResources().getColor(R.color.txt_gray));

        isTimes = false;
    }

    /**
     * 非连续模式按钮选择
     */
    private void chooseTimes(int times) {
        if (isTimes == true) {
            showPopupWidow(timesNumValue);
        } else {
            timesNumValue.setBackgroundResource(R.drawable.choosetimes_checked_bak);
            Drawable left = getResources().getDrawable(R.drawable.small_check_ico);
            Drawable right = getResources().getDrawable(R.drawable.downarrow_ico);
            left.setBounds(0, 0, left.getMinimumWidth(), left.getMinimumHeight());
            right.setBounds(0, 0, right.getMinimumWidth(), right.getMinimumHeight());
            timesNumValue.setCompoundDrawables(left, null, right, null);
            timesNumValue.setTextColor(getResources().getColor(R.color.txt_white));
            if (times != -1) {
                timesNumValue.setText(getResources().getStringArray(R.array.http_url_array)[times]);
            }

            isTimes = true;
        }
    }

    /**
     * exList长按事件监听
     */
    private OnItemLongClickListener exListLongTouchListener = new OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> arg0, final View arg1, int arg2, long arg3) {
            if (!isShowChart) {
                if (arg1.getTag(R.string.group_item_tag) != null) {
                    int groupPos = (Integer) arg1.getTag(R.string.group_item_tag); // 参数值是在setTag时使用的对应资源id号
                    final int roundId = (Integer) arg1.getTag(R.string.group_item_pid);
                    if (groupPos == 0) {// 长按的是父项
                        // popupGroupWindowInit(arg1);
                        // showListPopupWidow(arg1);
                        // mGroupPop = arg2;

                        new AlertDialog.Builder(HttpTestActivity.this)
                                .setTitle(R.string.dlg_note_title)
                                .setItems(getResources().getStringArray(R.array.group_array),
                                        new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog, int which) {
                                                dialog.dismiss();

                                                switch (which) {
                                                    case 0: {
                                                        mGroupPid = roundId;
                                                        ConfirmDelete();
                                                    }
                                                        break;
                                                    case 1: {
                                                    	HttpTestRoundInfoBean testInfo = getRoundById(roundId);
                                                        MyCommonUtil.share(HttpTestActivity.this,
                                                                getString(R.string.share),
                                                                setShareData(testInfo));
                                                    }
                                                        break;
                                                    case 2: {
                                                        reportGenerate(roundId);
                                                    }
                                                        break;
                                                }
                                            }
                                        }).show();

                        return true;
                    }
                }
            } else {
                Toast.makeText(HttpTestActivity.this, R.string.toast_note_testing, Toast.LENGTH_LONG)
                        .show();
            }

            return false;
        }
    };

    private HttpTestRoundInfoBean getRoundById(int id) {
    	HttpTestRoundInfoBean returnObject = null;
        if (groupList != null && groupList.size() > 0) {
            for (HttpTestRoundInfoBean element : groupList) {
                if (id == element.getPID()) {
                    returnObject = element;
                    break;
                }
            }
        }
        return returnObject;
    }

    /**
     * exList子Item点击
     */
    private OnChildClickListener childsListener = new OnChildClickListener() {
        @Override
        public boolean onChildClick(ExpandableListView parent, View v, int groupPosition,
                int childPosition, long id) {
            if (childPosition > 0) {
                Intent it = new Intent(HttpTestActivity.this, NetTestDetailActivity.class);
                HttpTestRoundInfoBean info = groupList.get(groupPosition);
                if (info != null) {
                    it.putExtra(NetTestDBConstant.TestRoundFiledName.pid, info.getPID());
                    it.putExtra(TestTimesFiledName.number, childPosition);
                    it.putExtra(MyCommonConstant.BottomIdxCode.bottom_dis,
                            MyCommonConstant.BottomIdxCode.BOTTOM_IDX_TEST_TOOL);
                }
                startActivity(it);
            }
            return true;
        }
    };

    /**
     * 网络切换监听广播监听
     */
    public class ConnectionChangeReceiver extends BroadcastReceiver {

        private String TAG = ConnectionChangeReceiver.class.getSimpleName();

        @Override
        public void onReceive(Context context, Intent intent) {

            try {
                Log.e(TAG, "网络状态改变");
                boolean success = false;
                // 获得网络连接服务
                ConnectivityManager connManager = (ConnectivityManager) context
                        .getSystemService(Context.CONNECTIVITY_SERVICE);
                // State state = connManager.getActiveNetworkInfo().getState();
                // 获取WIFI网络连接状态
                State state = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
                // 判断是否正在使用WIFI网络
                if (State.CONNECTED == state) {
                    success = true;
                }
                // 获取GPRS网络连接状态
                state = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
                // 判断是否正在使用GPRS网络
                if (State.CONNECTED != state) {
                    success = true;
                }
                if (refreshHandler != null) {
                    refreshHandler
                            .sendEmptyMessage(HttpTestActivityConstant.HandlerCode.HeadDispose);
                }
            } catch (Exception e) {
                // TODO: handle exception
            }
        }
    }

    /**
     * importdata广播接收器
     */
    class ImportDataReceiver extends BroadcastReceiver {
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(
                    MyCommonConstant.PrivateActionName.IMPORT_DATA_FINISH_BROAD)) {
                refreshHandler
                        .sendEmptyMessage(HttpTestActivityConstant.HandlerCode.listRefreshDispose);

            } else if (intent.getAction().equals(
                    MyCommonConstant.PrivateActionName.NET_TEST_ONE_ROUND_FINISH_BROAD)) {
                stopChartTimer();
                refreshHandler.sendEmptyMessageDelayed(HttpTestActivityConstant.HandlerCode.RoundDispose,1000l);
                Log.i("HttpTestActivity", "NET_TEST_ONE_ROUND_FINISH_BROAD");

            }
        }
    }

    /**
     * NetTest广播接收器
     */
    class NetTestServiceReceiver extends BroadcastReceiver {
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(
                    MyCommonConstant.PrivateActionName.HTTP_TEST_ONE_ROUND_FINISH_BROAD)) {
                refreshHandler.sendEmptyMessage(HttpTestActivityConstant.HandlerCode.RoundDispose);
                Log.i("HttpTestActivity", "NET_TEST_ONE_ROUND_FINISH_BROAD");

            } else if (intent.getAction().equals(
                    MyCommonConstant.PrivateActionName.HTTP_TEST_ONE_TIME_FINISH_BROAD)) {

                mTimeSuccess = intent.getBooleanExtra(
                        MyCommonConstant.PrivateActionName.HTTP_TEST_CURRENT_TIME_IS_SUCCESS, false);
                mTimeIdx = intent.getIntExtra(
                        MyCommonConstant.PrivateActionName.HTTP_TEST_CURRENT_TIME, 0);
                refreshHandler.sendEmptyMessage(HttpTestActivityConstant.HandlerCode.timeDispose);
                Log.i("HttpTestActivity", "NET_TEST_ONE_TIME_FINISH_BROAD");
            } else if (intent.getAction().equals(
                    MyCommonConstant.PrivateActionName.HTTP_TEST_SPEED_BROAD)) {
                mMaxSpeed = intent.getDoubleExtra(
                        MyCommonConstant.PrivateActionName.HTTP_TEST_MAX_SPEED_BROAD, 0);
                mMinSpeed = intent.getDoubleExtra(
                        MyCommonConstant.PrivateActionName.HTTP_TEST_MIN_SPEED_BROAD, 0);
                mAveSpeed = intent.getDoubleExtra(
                        MyCommonConstant.PrivateActionName.HTTP_TEST_AVERAGE_SPEED_BROAD, 0);

//                Log.i("HttpTestActivity", "HTTP_TEST_SPEED_BROAD");

            } else if (MyCommonConstant.PrivateActionName.HTTP_TEST_ONE_ROUND_BEGIN_BROAD
                    .equalsIgnoreCase(intent.getAction())) {

                refreshHandler
                        .sendEmptyMessage(HttpTestActivityConstant.HandlerCode.listRefreshDispose);
                Log.d("HttpTestActivity", "HTTP_TEST_ONE_ROUND_BEGIN_BROAD");
            }

        }
    }

    private void roundDispose() {
        CloseChart();
    }

    private void timeDispose() {
        refreshListData();
        if (mTimeSuccess) {
            String messasge = String.format(
                    getResources().getString(R.string.tims_success_message), mTimeIdx);

            Toast.makeText(HttpTestActivity.this, messasge, Toast.LENGTH_LONG).show();
        } else {
            String messasge = String.format(getResources().getString(R.string.tims_fail_message),
                    mTimeIdx);

            Toast.makeText(HttpTestActivity.this, messasge, Toast.LENGTH_LONG).show();
        }
    }

    private void stopTestServiceDispose() {
        if (SetUtil.getHttpTestRuningState(this)) {
            isShowChart = false;
            // 移除波形图
            lyChart.removeAllViews();
            // 关闭列表实时速度显示
            CloseListSpeed();
            // 关闭测试服务
            stopTest();
        } else {
            refreshHandler.sendEmptyMessage(HttpTestActivityConstant.HandlerCode.listRefreshDispose);
        }
    }

    /**
     * 更新信息handler
     */
    private Handler refreshHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (msg.what == HttpTestActivityConstant.HandlerCode.HeadDispose) {
                setHeadData();
            } else if (msg.what == HttpTestActivityConstant.HandlerCode.ChartRefreshDispose) {
                setChartViewData();
            } else if (msg.what == HttpTestActivityConstant.HandlerCode.RoundDispose) {
                roundDispose();
            } else if (msg.what == HttpTestActivityConstant.HandlerCode.timeDispose) {
                timeDispose();
            } else if (msg.what == HttpTestActivityConstant.HandlerCode.listRefreshDispose) {
                refreshListData();
            } else if (msg.what == HttpTestActivityConstant.HandlerCode.stopServiceDispose) {
                stopTestServiceDispose();
            } else if (msg.what == HttpTestActivityConstant.HandlerCode.startServiceDispose) {
                startHttpTest();
            }

        }
    };

    /**
     * 设置信号强度
     * 
     * @param _netStrong
     */
    public void setNetStrong(int _netStrong) {
        netStrong = _netStrong;
        if (tvSignalValue != null) {
            tvSignalValue.setText(String.valueOf(netStrong));
        }
    }

    /**
     * 获取信号强度
     * 
     * @return
     */
    public int getNetStrong() {
        return netStrong;
    }

    /**
     * 手机信号监听
     * 
     * @author zhangheng
     */
    public class HttpTestActivityPhoneStateListener extends PhoneStateListener {

        private int netStrong = 0;

        @Override
        public void onSignalStrengthsChanged(SignalStrength signalStrength) {
            super.onSignalStrengthsChanged(signalStrength);
            try {
                int asu = signalStrength.getGsmSignalStrength();
                netStrong = -113 + 2 * asu;
                setNetStrong(netStrong);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onCellLocationChanged(CellLocation location) {
            super.onCellLocationChanged(location);
        }
    }

    /**
     * 定位成功。
     * 
     * @param intent
     */
    protected void locationSuccess(Intent intent) {

    }

}
